/**
 * 类名：ImageUtil
 * 创建日期： 2014-11-22 下午7:15:35
 * 
 */
package com.erms.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.log4j.Logger;

/**
 * @author hmb<br>
 *         备注： 负责图片的读写、缩放、转换等
 * 
 */
public class ImageUtil {
	static Logger	logger	= LogUtil.getLogger(ImageUtil.class);

	public static ByteArrayInputStream toInputStream(BufferedImage image) {

		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
			ImageIO.write(image, "jpg", ios);
			return new ByteArrayInputStream(bos.toByteArray());
		} catch (IOException e) {
			logger.error("toInputStream + IOException", e);
		}
		return null;
	}

	public static BufferedImage getImage(File file) {

		if (file == null || !file.canRead()) return null;
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);
		} catch (Exception e) {
			logger.debug("不能正确读取图片：" + file.getPath());
		}
		return image;
	}

	public static BufferedImage getImage(File file, Integer maxWidthOrHeight) {

		BufferedImage image = getImage(file);
		if (image == null) { return null; }
		int width = image.getWidth();
		int height = image.getHeight();
		float scale = (float) maxWidthOrHeight / Math.max(width, height);
		logger.debug("缩放比例为：" + scale);
		return resize(image, scale);
	}

	public static BufferedImage getImage(File file, Float scale) {

		BufferedImage image = getImage(file);
		return resize(image, scale);
	}

	public static BufferedImage resize(BufferedImage image, float scale) {

		BufferedImage newImage = null;
		if (image == null) return null;
		int width = (int) (image.getWidth() * scale);
		int height = (int) (image.getHeight() * scale);
		newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		newImage.getGraphics().drawImage(
				image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,
				0, null);
		return newImage;
	}

}
